package framework.runtime;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import framework.utils.JsonUtil;

import java.io.IOException;

public class JsonObjectArraySerializer extends JsonSerializer<Object[]> {

    @Override
    public void serialize(Object[] values, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (values == null) {
            gen.writeNull();
            return;
        }
        if (values.length == 0) {
            gen.writeStartArray();
            gen.writeEndArray();
            return;
        }
        Object value = values[0];
        ObjectMapper mapper = JsonUtil.newMapper();
        mapper.configOverride(value.getClass()).setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.OBJECT));
        gen.writeRawValue(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(values));
    }

}
